package org.example.new_hbps_backend_reconstruction.controller.patient;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.example.new_hbps_backend_reconstruction.common.results.R;
import org.example.new_hbps_backend_reconstruction.entity.HeartRateLogsEntity;
import org.example.new_hbps_backend_reconstruction.service.HeartRateLogsService;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;

/**
 * @author 丁利军
 * @date 2025年10月11日 20:06
 * @description 患者心率数据
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("/patient/heartRateLogs" )
@Tag(description = "heartRateLogs" , name = "患者心率数据管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class HeartRateLogsController {

    private final HeartRateLogsService heartRateLogsService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param heartRateLogs 患者心率数据
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')" )
    public R getHeartRateLogsPage(@ParameterObject Page page, @ParameterObject HeartRateLogsEntity heartRateLogs) {
        LambdaQueryWrapper<HeartRateLogsEntity> wrapper = Wrappers.lambdaQuery();
        return R.ok(heartRateLogsService.page(page, wrapper));
    }


    /**
     * 通过id查询患者心率数据
     * @param hrlId id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{hrlId}" )
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')" )
    public R getById(@PathVariable("hrlId" ) Long hrlId) {
        return R.ok(heartRateLogsService.getById(hrlId));
    }

    /**
     * 新增患者心率数据
     * @param heartRateLogs 患者心率数据
     * @return R
     */
    @Operation(summary = "新增患者心率数据" , description = "新增患者心率数据" )
    //@SysLog("新增患者心率数据" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_add')" )
    public R save(@RequestBody HeartRateLogsEntity heartRateLogs) {
        return R.ok(heartRateLogsService.save(heartRateLogs));
    }

    /**
     * 修改患者心率数据
     * @param heartRateLogs 患者心率数据
     * @return R
     */
    @Operation(summary = "修改患者心率数据" , description = "修改患者心率数据" )
    //@SysLog("修改患者心率数据" )
    @PutMapping
    //@PreAuthorize("@pms.hasPermission('patient_heartRateLogs_edit')" )
    public R updateById(@RequestBody HeartRateLogsEntity heartRateLogs) {
        return R.ok(heartRateLogsService.updateById(heartRateLogs));
    }

    /**
     * 通过id删除患者心率数据
     * @param ids hrlId列表
     * @return R
     */
    @Operation(summary = "通过id删除患者心率数据" , description = "通过id删除患者心率数据" )
    //@SysLog("通过id删除患者心率数据" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_del')" )
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(heartRateLogsService.removeBatchByIds(CollUtil.toList(ids)));
    }


    /**
     * 导出excel 表格
     * @param heartRateLogs 查询条件
     * @param ids 导出指定ID
     * @return excel 文件流
     */
    //TODO 待完善
    //@ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_export')" )
    public List<HeartRateLogsEntity> export(HeartRateLogsEntity heartRateLogs, Long[] ids) {
        return heartRateLogsService.list(Wrappers.lambdaQuery(heartRateLogs).in(ArrayUtil.isNotEmpty(ids), HeartRateLogsEntity::getHrlId, ids));
    }

    @Operation(summary = "批量添加心率数据", description = "批量添加心率数据")
    @PostMapping("/add_heart_batches")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_add')")
    public R saveInBatches(@RequestBody List<HeartRateLogsEntity> data) {
        return R.ok(heartRateLogsService.saveBatch(data));
    }

    @Operation(summary = "全条件查询心率数据", description = "全条件查询心率数据")
    @PostMapping("/getByHeartRate")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')")
    public R getByUserFeedbackObject(@RequestBody HeartRateLogsEntity heartRateLogs) {
        LambdaQueryWrapper<HeartRateLogsEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.setEntity(heartRateLogs);
        return R.ok(heartRateLogsService.list(wrapper));
    }

    @Operation(summary = "查询某一周的所有心率", description = "查询某一周的所有心率")
    @GetMapping("/weekly_heart_rate_data")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')")
    public R getWeeklyHeartRateData(@RequestParam int weeksAgo, @RequestParam Long patientUid) {
        JSONArray result = heartRateLogsService.getWeeklyHeartRateData(weeksAgo, patientUid);
        return R.ok(result);
    }

    @Operation(summary = "查询某一个月的所有心率", description = "查询某一个月的所有心率")
    @GetMapping("/monthly_heart_rate_data")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')")
    public R getMonthlyHeartRateData(@RequestParam int monthsAgo, @RequestParam Long patientUid) {
        JSONArray result = heartRateLogsService.getMonthlyHeartRateData(monthsAgo, patientUid);
        return R.ok(result);
    }

    @Operation(summary = "查询某一年的所有心率", description = "查询某一年的所有心率")
    @GetMapping("/yearly_heart_rate_data")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')")
    public R getYearlyHeartRateData(@RequestParam int yearsAgo, @RequestParam Long patientUid) {
        JSONArray result = heartRateLogsService.getYearlyHeartRateData(yearsAgo, patientUid);
        return R.ok(result);
    }

    @Operation(summary = "查询最新的心率数据", description = "查询最新的心率数据")
    @GetMapping("/get_newly_heart_rate_data")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')")
    public R getNewlyHeartRateData(@RequestParam Long patientUid) {
        return R.ok(heartRateLogsService.getNewlyHeartRateData(patientUid));
    }

    @Operation(summary = "查询某一天的某位患者的心率的平均值", description = "查询某一天的某位患者的心率的平均值")
    @GetMapping("/daily_avg_heart_rate")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')")
    public R getDailyAverageHeartRate(@RequestParam LocalDate date, @RequestParam Long patientUid) {
        JSONObject result = heartRateLogsService.getDailyAverageHeartRate(date, patientUid);
        return R.ok(result);
    }

    @Operation(summary = "查询某一周的某位患者的心率的平均值", description = "查询某一周的某位患者的心率的平均值")
    @GetMapping("/weekly_avg_heart_rate")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')")
    public R getWeeklyAverageHeartRateByDay(@RequestParam LocalDate anyDateInWeek, @RequestParam Long patientUid) {
        return R.ok(heartRateLogsService.getWeeklyAverageHeartRateByDay(anyDateInWeek, patientUid));
    }

    @Operation(summary = "查询某一个月的某位患者的每周段的心率的平均值", description = "查询某一个月的某位患者的每周段的心率的平均值")
    @GetMapping("/monthly_avg_heart_rate_by_week")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')")
    public R getMonthlyAverageHeartRateByWeek(@RequestParam YearMonth yearMonth, @RequestParam Long patientUid) {
        return R.ok(heartRateLogsService.getMonthlyAverageHeartRateByWeek(yearMonth, patientUid));
    }

    @Operation(summary = "查询某一年的每个月的心率的平均值", description = "查询某一年的每个月的心率的平均值")
    @GetMapping("/yearly_avg_heart_rate_by_month")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')")
    public R getYearlyAverageHeartRateByMonth(@RequestParam int yearsAgo, @RequestParam Long patientUid) {
        return R.ok(heartRateLogsService.getYearlyAverageHeartRateByMonth(yearsAgo, patientUid));
    }

    @Operation(summary = "统计今天连续低心率的患者", description = "统计今天所有患者连续低心率的次数")
    @GetMapping("/todayConsecutiveAbnormalities")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')")
    public R getTodayConsecutiveAbnormalities(@RequestParam Long doctorUid) {
        JSONArray result = heartRateLogsService.getDailyConsecutiveAbnormalities(doctorUid);
        return R.ok(result);
    }

    @Operation(summary = "查询心率类型人数" , description = "查询心率类型人数" )
    @GetMapping("/{doctorUid}/patient/heartRate/stats")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')" )
    public R getHeartRateStatistics(@PathVariable("doctorUid") Long doctorUid) {
        JSONObject result = heartRateLogsService.getHeartRateStatistics(doctorUid);
        return R.ok(result);
    }

    @Operation(summary = "查询特别关系心率类型人数" , description = "查询特别关系心率类型人数" )
    @GetMapping("/{doctorUid}/carepatient/heartRate/stats")
    @PreAuthorize("@pms.hasPermission('patient_heartRateLogs_view')" )
    public R getcareHeartRateStatistics(@PathVariable("doctorUid") Long doctorUid) {
        JSONObject result = heartRateLogsService.getcareHeartRateStatistics(doctorUid);
        return R.ok(result);
    }
}